package com.malou.server.ventas.modeloprenda;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.malou.server.base.util.ThumbNail2;

public class UploadFile extends HttpServlet {

	private static final long serialVersionUID = 9000485543520772352L;

	private static final String TMP_DIR_PATH = "tmp";
	private File tmpDir;
	private static final String DESTINATION_DIR_PATH ="/upload";
	private File destinationDir;
 
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		tmpDir = new File(TMP_DIR_PATH);
		if(!tmpDir.isDirectory()) {
			throw new ServletException(TMP_DIR_PATH + " is not a directory");
		}
		String realPath = getServletContext().getRealPath(DESTINATION_DIR_PATH);
		destinationDir = new File(realPath);
		if(!destinationDir.isDirectory()) {
			throw new ServletException(DESTINATION_DIR_PATH+" is not a directory");
		}
 
	}
	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response)  
    throws ServletException, IOException  
    {
		
    }
	
	@SuppressWarnings("rawtypes")
	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response)  
    throws ServletException, IOException  
    {
		PrintWriter out = response.getWriter();
	    response.setContentType("text/html;charset=UTF-8");
	    //out.println("Servlet File Upload Example using Commons File Upload");
	    //out.println();
 
		DiskFileItemFactory  fileItemFactory = new DiskFileItemFactory ();
		/*
		 *Set the size threshold, above which content will be stored on disk.
		 */
		fileItemFactory.setSizeThreshold(1*1024*1024); //1 MB
		/*
		 * Set the temporary directory to store the uploaded files of size above threshold.
		 */
		fileItemFactory.setRepository(tmpDir);
 
		ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
		try {
			/*
			 * Parse the request
			 */
			List items = uploadHandler.parseRequest(request);
			Iterator itr = items.iterator();
			while(itr.hasNext()) {
				FileItem item = (FileItem) itr.next();
				/*
				 * Handle Form Fields.
				 */
				if(item.isFormField()) {
					out.println("File Name = "+item.getFieldName()+", Value = "+item.getString());
				} else {
					//Handle Uploaded files.
					String fileName = item.getName();
					//out.print(item.getName());
//					out.println("Field Name = "+item.getFieldName()+
//						", File Name = "+item.getName()+
//						", Content type = "+item.getContentType()+
//						", File Size = "+item.getSize());
					/*
					 * Write file to the ultimate location.
					 */
					
					String uuid = UUID.randomUUID().toString();
					int dot = fileName.lastIndexOf(".");
					String extension = fileName.substring(dot + 1);
					String newName = uuid+"."+extension;
					String thumbName = uuid+"-thumb."+extension;
					File file = new File(destinationDir, newName);
					item.write(file);
					
					new ThumbNail2().createThumbnail(destinationDir+"/"+newName, destinationDir+"/"+thumbName, 209, 252);
					out.print(thumbName);
				}
				out.close();
			}
		}catch(FileUploadException ex) {
			log("Error encountered while parsing the request",ex);
		} catch(Exception ex) {
			log("Error encountered while uploading file",ex);
		}
 
	}
    
}
